package com.more.offer.algorithm.leetcode.lcode04;

/**
 * @Author: yinpeng
 * @Date: 2019/9/26 11:21
 * @Description: TODO
 **/
public class Solution_01 {
	public static double findMedianSortedArrays(int[] nums1, int[] nums2) {

		if(nums1.length == 0){
			if(nums2.length % 2 == 0){
				return (nums2[nums2.length / 2 -1] + nums2[nums2.length / 2]) / 2.0;
			}else{
				return nums2[nums2.length / 2 ];
			}
		}

		if(nums2.length == 0){
			if(nums1.length % 2 == 0){
				return (nums1[nums1.length / 2 -1] + nums1[nums1.length / 2]) / 2.0;
			}else{
				return nums1[nums1.length / 2 ];
			}
		}

		//数组合并
		int count = 0;
		int i=0,j=0;
		int []  newArray = new int[nums1.length+nums2.length];
		while(count<(nums1.length+nums2.length)){
			if(i==nums1.length){
				while(j<nums2.length){
					newArray[count++] = nums2[j++];
				}
				break;
			}

			if(j==nums2.length){
				while(i<nums1.length){
					newArray[count++] = nums1[i++];
				}
				break;
			}

			if(nums1[i] < nums2[j]){
				newArray[count++] = nums1[i++];
			}else{
				newArray[count++] = nums2[j++];
			}
		}

		if(count%2 == 0){
			return (newArray[count/2 - 1] + newArray[count/2]) / 2.0;
		}else{
			return newArray[count/2];
		}
	}

	public static void main(String[] args) {
		double medianSortedArrays = findMedianSortedArrays(new int[]{1, 2}, new int[]{3,4});
		System.out.println(medianSortedArrays);
	}
}
